<template>
	<view class="container">
		<!-- 导航栏 -->
		<view class="navTop">
			<u-navbar title="公司详情" title-color="#333" bg-color="#fff" :is-back="true" :border-bottom="false"></u-navbar>
		</view>
		<!-- 主要内容 -->
		<scroll-view scroll-y="true" :style="{height:swiperHeight -10 +'px'}" enhanced="{{true}}"
			show-scrollbar="{{false}}" v-if="formConfig">
			<view class="content">
				<view class="configItem" v-for="category in groupedFields" :key="category.name">
					<u-section line-color="#2979ff" color="#303133" font-size="32" :title="category.name"
						:right="false"></u-section>
					<view class="section">
						<view class="section-item" v-for="field in category.fields" :key="field.key">
							<view class="company-header" v-if="field.renderType === 'img'">
								<view class="company-name">{{ field.label }}</view>
								<image v-if="companyForm[field.key]" :src="companyForm[field.key]" mode="aspectFill"
									class="company-logo" />
								<view v-else class="logo-placeholder">
									<u-icon name="account-fill" size="60" color="#ccc"></u-icon>
								</view>
							</view>
							<view class="supply-chain" v-else-if="field.renderType === 'strArr'">
								<view class="chain-item">
									<view class="chain-title">
										<u-icon :name="getTagIcon(field)" :color="getTagIconColor(field)"
											size="28"></u-icon>
										<text>{{field.label}}</text>
									</view>
									<view class="chain-content">
										<view class="tag"
											v-for="(c,index) in getArrayFromString(companyForm[field.key])"
											:key="index">
											<u-tag :type="getTagType(field)" shape="circleLeft " :text="c"
												:mode="getTagEffect(field)" />
										</view>
									</view>
								</view>
							</view>
							<!-- 对象数组字段 -->
							<view class="objArr" v-else-if="field.renderType === 'objArr'">
								<view class="obj-list">
									<view class="obj-card"
										v-for="(objContent, index) in fromConfigIsArray(companyForm[field.key])"
										:key="index">
										<view class="obj-content">
											<view class="info">
												<view :class="subField.key" v-for="subField in field.formConfig"
													:key="subField.key">
													{{objContent[subField.key]}}
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
							<!-- 数字输入字段 -->
							<view class="numberBox" v-else-if="field.renderType === 'number'">
								<view class="info-label">{{ field.label }}</view>
								<view class="info-content text-number">
									{{ formatNumber(companyForm[field.key]) }}
									<span class="text-unit">{{ field.unit }}</span>
								</view>
							</view>
							<view class="textareaBox labelBox" v-else-if="field.renderType === 'textarea'">
								<view class="info-label">{{ field.label }}：</view>
								<view class="info-content text-textarea">
									{{ companyForm[field.key] }}
								</view>
							</view>
							<view class="labelBox" v-else>
								<view class="info-label">{{ field.label }}：</view>
								<view class="info-content text-content">
									{{ companyForm[field.key] }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		toast,
		toastC,
		toastload,
		closeload
	} from "../../utils/common"
	import {
		getCustomerInfo,
		getColumns
	} from "@/api/index.js"
	export default {
		data() {
			return {
				formConfig: [],
				companyForm: {},
				swiperHeight: 0,
			}
		},
		computed: {
			// 按分类分组字段
			groupedFields() {
				const fields = this.formConfig.filter(field => field.isShow && field.key !== "operation")
				const categories = new Map()

				fields.forEach(field => {
					if (!categories.has(field.category)) {
						categories.set(field.category, [])
					}
					categories.get(field.category)?.push(field)
				})

				return Array.from(categories.entries()).map(([name, fields]) => ({
					name,
					fields
				}))
			}
		},
		onLoad(options) {
			this.getInfo(options.id)

		},
		onReady() {
			this.initBoxSize()
		},
		methods: {
			async getInfo(id) {
				try {
					toastload("数据加载中...")
					const res = await getColumns({
						permission: uni.getStorageSync("permission")
					})
					this.formConfig = res.data

					// 再获取渲染数据
					const comres = await getCustomerInfo({
						userId: id
					})
					this.companyForm = comres.data

				} catch (error) {
					toast("获取公司信息失败" + error)
				} finally {
					closeload()
				}
			},
			// 初始化尺寸
			async initBoxSize() {
				const measure = (selector) => new Promise(resolve =>
					uni.createSelectorQuery()
					.select(selector)
					.boundingClientRect(data => resolve(data?.height || 0))
					.exec()
				);

				try {
					const [navH, boxH, footerH] = await Promise.all([
						measure('.navTop'),
						measure('.container')
					]);

					this.swiperHeight = boxH - navH
				} catch (error) {
					toast("高度异常:" + error)
					this.swiperHeight = 300;
				}
			},
			// 标签相关方法
			getArrayFromString(str) {
				return str ? str.split(",").filter(item => item.trim() !== "") : []
			},
			// 处理数据
			fromConfigIsArray(data) {
				if (typeof data === "string") {
					try {
						return JSON.parse(data); // 尝试解析 JSON 字符串
					} catch (e) {
						console.error("Invalid JSON string:", e);
						return []; // 解析失败返回空数组（或原数据）
					}
				}
				return Array.isArray(data) ? data : []; // 如果不是数组，返回空数组（或原数据）
			},
			getTagIconColor(field) {
				return field.key.includes("up") ? "#19be6b" : field.key.includes("down") ? "#f56c6c" : "#19be6b";
			},
			// 获取icon样式
			getTagIcon(field) {
				return field.key.includes("up") ? "arrow-up" : field.key.includes("down") ? "arrow-down" : "bookmark";
			},
			// 获取标签样式
			getTagEffect(field) {
				return field.key.includes("up") ? "plain" : field.key.includes("down") ? "light" : "plain";
			},

			// 获取标签类型
			getTagType(field) {
				return field.key.includes("upstream") ? "success" : "warning";
			},
			// 格式化数字
			formatNumber(value) {
				if (value === undefined || value === null || value === "") return "0";
				return Number(value).toLocaleString();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #f5f5f5;
		height: 100vh;
	}

	.content {
		padding: 20rpx;
	}

	.section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
		margin-top: 10rpx;

		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 24rpx;
			color: #333;
			position: relative;
			padding-left: 20rpx;

			&::before {
				content: '';
				position: absolute;
				left: 0;
				top: 8rpx;
				height: 32rpx;
				width: 6rpx;
				background-color: #2979ff;
				border-radius: 3rpx;
			}
		}
	}

	.company-header {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 30rpx;

		.company-logo {
			width: 160rpx;
			height: 160rpx;
			border-radius: 16rpx;
			margin-bottom: 20rpx;
			border: 1rpx solid #eee;
		}

		.logo-placeholder {
			width: 160rpx;
			height: 160rpx;
			border-radius: 16rpx;
			background-color: #f9f9f9;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 20rpx;
			border: 1rpx dashed #ddd;
		}

		.company-name {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			text-align: center;
		}
	}

	.description-content {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
	}

	.supply-chain {
		.chain-item {
			margin-bottom: 30rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.chain-title {
				display: flex;
				align-items: center;
				font-size: 28rpx;
				font-weight: bold;
				margin-bottom: 10rpx;
				color: #333;

				text {
					margin-left: 10rpx;
				}
			}

			.chain-content {
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				gap: 10rpx;
				font-size: 26rpx;
				color: #666;
				line-height: 1.6;
				white-space: pre-line;
				padding-left: 38rpx;
			}
		}
	}

	.obj-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.obj-card {
		background-color: #f9f9f9;
		border-radius: 12rpx;
		padding: 24rpx;
		position: relative;

		.obj-content {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;

			.info {
				display: flex;
				flex-direction: column;
				flex: 1;
				line-height: 48rpx;
			}

			.name {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 6rpx;
			}

		}
	}

	.labelBox {
		display: flex;
		align-items: flex-start;
	}

	.info-label {
		margin-bottom: 6px;
		font-size: 16px;
		font-weight: 600;
	}

	.info-content {
		font-size: 14px;
		line-height: 1.5;
		min-height: 20px;

		.text-textarea {
			font-size: 14px;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			/* 限制显示的行数 */
			overflow: hidden;
			text-overflow: ellipsis;
		}

		&.text-number {
			font-weight: 600;
			font-size: 18px;
			color: #009688;
		}

		&.text-content {
			font-size: 16px;
			text-overflow: ellipsis;
			overflow: hidden;
			white-space: nowrap;
		}
	}

	.text-unit {
		margin-left: 4px;
		font-size: 12px;
		color: #909399;
	}
</style>